package cn.fengkuok.core.web.struts;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fengkuok.core.orm.Page;
import cn.fengkuok.core.utils.reflection.ReflectionUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 普通Action继承此类即可
 * 
 * @param BaseAction所管理的对象类型
 *            .
 * @author $Author: GuoFeng $
 */
public class BaseAction<T extends Object> extends ActionSupport implements
		ModelDriven<T> {

	private static final long serialVersionUID = 1025478307722403630L;
	/** * 日志. */
	private static Log logger = LogFactory.getLog(BaseAction.class);
	/** * 持久类. */
	protected T entity;

	/** * 持久类类型. */
	protected Class<T> entityClass;

	/** Page */
	protected Page<T> page;

	/** * 构造方法. */
	public BaseAction() {
		this.entityClass = ReflectionUtils.getSuperClassGenricType(this.getClass());

		if (page == null) {
			page = new Page<T>();
		}
	}

	public Page<T> getPage() {
		return page;
	}

	public void setPage(Page<T> page) {
		this.page = page;
	}

	/**
	 * 获取当前登录用户的信息
	 * 
	 * @return 当前登录用户
	 */
	public static Object getLoginedUser() {

		return getValueFromSession("user");
	}

	/**
	 * 获取session
	 * 
	 * @return session
	 */
	public static Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}

	/**
	 * 根据指定key从session中获取值
	 * 
	 * @return session
	 */
	public static Object getValueFromSession(String key) {
		return getSession().get(key);
	}

	/**
	 * 向session 设置属性值
	 * 
	 * @param name
	 *            *
	 * @param value
	 */
	public static void setValueToSession(String name, Object value) {
		Map<String, Object> session = getSession();
		session.put(name, value);
	}

	/**
	 * 获取指定参数值
	 * 
	 * @param parameter
	 *            参数
	 * @return 值
	 */
	public static Object getParameterValue(String parameter) {
		ActionContext ctx = ActionContext.getContext();
		Map<String, Object> map = ctx.getParameters();
		return map.get(parameter);
	}

	public T getModel() {
		try {
			if (entity == null) {
				entity = (T) entityClass.newInstance();
			}
		} catch (Exception ex) {
			logger.error(ex, ex);
		}

		return entity;
	}

}
